import { _decorator, Component, Node, Prefab, instantiate, Vec3 } from 'cc';
import { BaseEffect } from '../effects/BaseEffect';

const { ccclass, property } = _decorator;

/**
 * 特效系统
 * 
 * 功能：
 * 1. 管理游戏中的所有特效
 * 2. 处理特效的创建和回收
 * 3. 控制特效的播放和停止
 * 4. 优化特效性能
 * 
 * 特点：
 * 1. 对象池管理
 * 2. 自动回收机制
 * 3. 批量渲染优化
 * 4. 动态特效参数
 */
@ccclass('EffectSystem')
export class EffectSystem extends Component {
    @property({type: [Prefab]})
    private effectPrefabs: Prefab[] = [];

    private effectMap: Map<string, Prefab> = new Map();

    start() {
        this.initEffectMap();
    }

    private initEffectMap() {
        this.effectPrefabs.forEach(prefab => {
            this.effectMap.set(prefab.name, prefab);
        });
    }

    public playEffect(effectName: string, position: Vec3, rotation: number = 0): BaseEffect | null {
        const prefab = this.effectMap.get(effectName);
        if (!prefab) {
            console.warn(`Effect ${effectName} not found!`);
            return null;
        }

        const effectNode = instantiate(prefab);
        effectNode.setPosition(position);
        effectNode.setRotationFromEuler(0, 0, rotation);
        this.node.addChild(effectNode);

        const effect = effectNode.getComponent(BaseEffect);
        if (effect) {
            effect.play();
        }

        return effect;
    }

    public stopEffect(effect: BaseEffect) {
        if (effect && effect.isValid) {
            effect.stop();
        }
    }
} 